<template>
  <view class="uni-container">
   <uni-forms ref="form" :model="formData" validateTrigger="bind" label-width="120px">
     <uni-forms-item name="name" label="姓名" required>
       <uni-easyinput placeholder="客户全名" v-model="formData.name"></uni-easyinput>
     </uni-forms-item>
     <uni-forms-item name="phone" label="手机号" required>
       <uni-easyinput placeholder="客户手机号码" v-model="formData.phone"></uni-easyinput>
     </uni-forms-item>
	 <uni-forms-item name="city" label="所在地" required>
	   <uni-data-checkbox v-model="formData.city" :localdata="formOptions.cityOptions"></uni-data-checkbox>
	 </uni-forms-item>
    <uni-forms-item name="type" label="客户分类" required>
      <uni-data-checkbox v-model="formData.type" :localdata="formOptions.typeOptions"></uni-data-checkbox>
    </uni-forms-item>
    <uni-forms-item name="level" label="客户级别" required>
      <uni-data-checkbox v-model="formData.level" :localdata="formOptions.levelOptions"></uni-data-checkbox>
    </uni-forms-item>
     <uni-forms-item name="status" label="客户状态" required>
       <uni-data-checkbox v-model="formData.status" :localdata="formOptions.status_localdata"></uni-data-checkbox>
     </uni-forms-item>
     <uni-forms-item name="debt_info" label="负债情况">
      <uni-data-select
      			 :localdata="formOptions.debt_localdata"
      			 v-model="formData.debt_info"
       />
     </uni-forms-item>
     <uni-forms-item name="repayment_date" label="还款日">
       <uni-datetime-picker return-type="timestamp" v-model="formData.repayment_date"></uni-datetime-picker>
     </uni-forms-item>
     <uni-forms-item name="birthday" label="生日">
       <uni-datetime-picker return-type="timestamp" v-model="formData.birthday"></uni-datetime-picker>
     </uni-forms-item>
     <uni-forms-item name="associated_users" label="关联人">
		  <uni-data-select
			 collection="uni-id-users"
			 field="_id as value, nickname as text"
			 v-model="formData.associated_users"
		   />
     </uni-forms-item>
   <!--  <uni-forms-item name="spouse" label="配偶信息">
      <uni-easyinput v-model="formData.spouse"></uni-easyinput>
     </uni-forms-item>
     <uni-forms-item name="company_info" label="企业信息">
       <uni-easyinput v-model="formData.company_info"></uni-easyinput>
     </uni-forms-item>
	 <uni-forms-item name="is_public" label="公海池">
	   <switch @change="binddata('is_public', $event.detail.value)" :checked="formData.is_public"></switch>
	 </uni-forms-item> -->
	 <uni-forms-item name="create_date" label="创建时间">
	   <uni-datetime-picker return-type="timestamp" v-model="formData.create_date" disabled></uni-datetime-picker>
	 </uni-forms-item>
     <view class="uni-button-group">
       <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
       <navigator open-type="navigateBack" style="margin-left: 15px;">
         <button class="uni-button" style="width: 100px;">返回</button>
       </navigator>
     </view>
   </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/mydb-customer.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'mydb-customer';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "name": "",
        "phone": "",
        "id_card": "",
        "type": [],
        "status": "",
        "source": "",
        "debt_info": "",
		"level":"",
		"city":"1",
        "repayment_date": null,
        "birthday": null,
        "associated_users": "",
        "is_public": false,
        "spouse": null,
        "company_info": null,
		"create_date":null,
      }
      return {
        formData,
        formOptions: {
         "typeOptions": [
			 { text: '信贷', value: 'credit' },
			 { text: '抵押', value: 'mortgage' },
			 { text: '现金业务', value: 'cash' },
			 { text: '企业融资', value: 'company' }
			],
			"levelOptions": [
			  { text: 'A级', value: 'A' },
			  { text: 'B级', value: 'B' },
			  { text: 'C级', value: 'C' },
			  { text: 'D级', value: 'D' }
			],
			"cityOptions": [
			  { text: '本地', value: '1' },
			  { text: '异地', value: '2' }
			],
         "status_localdata": [
           {
             "value": "potential",
             "text": "潜在"
           },
           {
             "value": "to_follow",
             "text": "跟进中"
           },
           {
             "value": "intention",
             "text": "意向"
           },
           {
             "value": "visit",
             "text": "上门"
           },
           {
             "value": "deal",
             "text": "成交"
           }
         ],
         "source_localdata": [
           {
             "value": "online",
             "text": "线上"
           },
           {
             "value": "channel",
             "text": "渠道"
           },
           {
             "value": "tel_sales",
             "text": "电话"
           },
           {
             "value": "wechat",
             "text": "微信"
           },
           {
             "value": "referral",
             "text": "转介绍"
           }
         ],
		 "debt_localdata": [
		   {
		     "value": "0",
		     "text": "无负债"
		   },
		   {
		     "value": "1",
		     "text": "小于10w"
		   },
		   {
		     "value": "2",
		     "text": "小于50w"
		   },
		   {
		     "value": "3",
		     "text": "小于100w"
		   },
		   {
		     "value": "4",
		     "text": "超过200w"
		   }
		 ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
		value.update_date=new Date().getTime()
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
